package one.chapter_1.stack;

import java.util.Iterator;

public class ResizingArrayStack<T> implements Iterable<T> {
    private static final int DEFAULT_SIZE = 10;
    private T[] data;
    private int pos;

    public ResizingArrayStack() {
        data = (T[]) new Object[DEFAULT_SIZE];
    }

    public void push(T item) {
        //判断是否需要扩容
        if (pos >= data.length - 1) {//已经满了
            int newSize = 2*data.length;//data.length + data.length / 2;
            resizeArray(newSize);
        }

        data[pos++] = item;

    }

    public T pop() {
        pos--;
        T item = data[pos];
        data[pos] = null;

        //判断容量是否大于现有数据长度的4倍
        if (pos!=0 && pos*4<data.length){
            int newSize=data.length/2;
            resizeArray(newSize);
        }
        return item;
    }


    private void resizeArray(int newSize) {

        T[] newArray = (T[]) new Object[newSize];
        System.arraycopy(data, 0, newArray, 0, data.length);

        data = newArray;

        System.out.println("newSize:"+newSize);
    }

    public Iterator<T> iterator() {
        return new Iter();
    }

    private class Iter implements Iterator<T>{

        public boolean hasNext() {
            return pos>0;
        }

        public T next() {
            return data[--pos];
        }

        public void remove() {

        }
    }


    public static void main(String [] args){

        int [] data={1,2,3,4,5,6,7,8,9,10,11};
        ResizingArrayStack<Integer> stack=new ResizingArrayStack<Integer>();
        for (int d:data){
            stack.push(d);
        }

        for (Integer d:stack){
            System.out.println(d);
        }

    }
}
